package com.devilloki.viki.overspeedalert.fragments;

import android.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.devilloki.viki.overspeedalert.Events.GpsInfoEvent;
import com.devilloki.viki.overspeedalert.R;
import com.devilloki.viki.overspeedalert.tools.DataConvert;
import com.devilloki.viki.overspeedalert.tools.MY_NAMES;
import com.devilloki.viki.overspeedalert.tools.SettingsHelper;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**显示行驶里程的fragment
 * Created by viki on 2016/3/24.
 */
public class DisplayTotalDistanceFragment extends Fragment {
    /**
     * 显示行程总里程的TextView
     */
    private TextView tvTotalDistance=null;
    /**
     * 用于在SharedPreferences存储数据的工具类
     */
    private SettingsHelper setting =null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.display_distance, container, false);
        setting = new SettingsHelper(this.getActivity());
        tvTotalDistance= (TextView) view.findViewById(R.id.tv_total_distance);
        if(null!=savedInstanceState){
            tvTotalDistance.setText(
                    savedInstanceState.getString(
                            MY_NAMES.KEY_GPS_INFO,MY_NAMES.DATA_Default_LngAndLat));
        }
        /**
         * 必须事先在assets底下创建一fonts文件夹 并放入要使用的字体文件(.ttf)
         * 并提供相对路径给creatFromAsset()来创建Typeface对象
         */
        Typeface fontFace = Typeface.createFromAsset(this.getActivity().getAssets(),
                MY_NAMES.FONTS_LCD);
        // 字体文件必须是true type font的格式(ttf)；
        // 当使用外部字体却又发现字体没有变化的时候(以 Droid Sans代替)，通常是因为
        // 这个字体android没有支持,而非你的程序发生了错误
        tvTotalDistance.setTypeface(fontFace);
        return view;
    }
    /**
     * 根据位置位置的变化更新界面
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventDisplayDistance(GpsInfoEvent event) {

        //行程的总里程
        double distance=Double.valueOf(setting.getString(MY_NAMES.KEY_TRACK_DISTANCE, MY_NAMES.DATA_Default_LngAndLat));
        //将m转换为Km
        distance=distance/1000;
        tvTotalDistance.setText(DataConvert.formatData(distance, 1));


    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString(MY_NAMES.KEY_GPS_INFO,String .valueOf(tvTotalDistance.getText()));
    }
}
